package com.hqyj.javaSpringBoot.interceptor;

import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *ViewMappingInterceptor
 * 自动封装template路径
 * 约定：目标页面的相对路径地址与path路径一致
 */
@Component
public class ViewMappingInterceptor implements HandlerInterceptor {

    private final static Logger LOGGER= LoggerFactory.getLogger(ViewMappingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request
            , HttpServletResponse response,
            Object handler) throws Exception {
        LOGGER.debug("=======preHandle=======");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        LOGGER.debug("=========postHandle=========");

        //判断请求是否返回 view，如果是rest接口||redirect ||forWord，则不作处理
        if (modelAndView==null ||
                modelAndView.getViewName().startsWith("redirect")
                ||modelAndView.getViewName().startsWith("forward")){
            return;
        }
        //从请求中得到path
        String path = request.getServletPath();
        //判断modelMap中是否有设置template，如果已有，则无需设置
        String template = (String) modelAndView.getModelMap().get("template");
        if (StringUtils.isBlank(template)){
            path=path.startsWith("/")?path.substring(1):path;
            modelAndView.getModelMap().addAttribute("template",path);
        }
        //在modelMap中设置template，值为path


    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        LOGGER.debug("========afterCompletion=========");
    }
}
